package pyip.lib.javalearn.aop.dynamicproxy.spring.introduction;

import org.springframework.aop.framework.ProxyFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Client {

    public static void main(String[] args) {
         declarationPattern();
//        programPattern();
    }

    private static void declarationPattern() {
        ApplicationContext context = new ClassPathXmlApplicationContext("pyip/lib/javalearn/aop/dynamicproxy/spring/introduction/aop-introduction.xml");
        GreetingIntroductionImpl greeting = (GreetingIntroductionImpl) context.getBean("greetingProxy"); // 注意：转型为目标类，而并非它的 Greeting 接口
        greeting.sayHello("Jack");

        Apology apology = (Apology) greeting; // 将目标类强制向上转型为 Apology 接口（这是引入增强给我们带来的特性，也就是“接口动态实现”功能）
        apology.saySorry("Jack");
        ((ClassPathXmlApplicationContext) context).close();
    }

    private static void programPattern() {
        ProxyFactory proxyFactory = new ProxyFactory(); // 创建代理工厂
        proxyFactory.setTarget(new GreetingIntroductionImpl()); // 射入目标类对象
        proxyFactory.addAdvice(new GreetingIntroAdvice());// 添加抛出增强
        proxyFactory.setInterfaces(new Class[] { Apology.class });
        proxyFactory.setProxyTargetClass(true);

        GreetingIntroductionImpl greeting = (GreetingIntroductionImpl) proxyFactory.getProxy();
        greeting.sayHello("Jack");

        Apology apology = (Apology) greeting;
        // 调用代理的方法
        apology.saySorry("Jack");
    }
}